﻿Imports AjaxControlToolkit
Imports System.Collections.ObjectModel

Public Class AccessRecords
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'check authentication
        If AuthenticationValidator.CheckIfAuthorized(Me, "AccessRecords") = False Then
            Me.Response.Redirect("AccessDeniedMsg.aspx")
        End If

        If Not Me.IsPostBack Then
            Refresh_Passes()
            Refresh_AccessRecords()
            Refresh_AuthorizedByList()
            info_Label.Text = ""
            Timer1.Enabled = True
        End If



    End Sub

    Private Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
        Timer1.Enabled = False
    End Sub

    <System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()> _
    Public Shared Function GetCustomerCompletionList(ByVal prefixText As String, _
                                             ByVal count As Integer, _
                                             ByVal contextKey As String) As String()
        'get customers
        Dim db As New DbHelper
        Dim customers As Collections.ObjectModel.Collection(Of CustomerType) = db.GetCustomersList
        Dim sCustomers = (From c As CustomerType In customers _
                          Where (c.IdNumber.ToLower.Contains(prefixText.ToLower)) _
                             Or (c.Name.ToLower.Contains(prefixText.ToLower)) _
                             Or (c.Telephone.ToLower.Contains(prefixText.ToLower)) _
                          Order By c.Name _
                          Select c).Take(count)

        Dim res As New List(Of String)
        If (sCustomers IsNot Nothing) _
            AndAlso (sCustomers.Count > 0) Then
            Dim cArray(sCustomers.Count)() As String
            For i As Integer = 0 To sCustomers.Count - 1
                Dim c As CustomerType = sCustomers(i)
                Dim cusItem As String = AutoCompleteExtender.CreateAutoCompleteItem(c.Text, c.CustomerId.ToString)
                res.Add(cusItem)
            Next
        End If
        Return res.ToArray

    End Function

    Private Sub Refresh_Passes()

        passNo_DropDownList.ClearSelection()
        Dim db As New DbHelper
        Dim passes As Collection(Of PassType) = db.GetPassesList_Available
        If (passes IsNot Nothing) _
            AndAlso (passes.Count > 0) Then
            With passNo_DropDownList
                .DataSource = Nothing
                .DataBind()
                .DataSource = passes
                .DataTextField = "Text"
                .DataValueField = "PassId"
                .DataBind()
            End With
        End If

    End Sub

    Private Sub Refresh_AuthorizedByList()

        authorizedBy_DropDownList.ClearSelection()
        Dim db As New DbHelper
        Dim users As Collection(Of UserType) = db.GetUsersListAuthorizable
        If (users IsNot Nothing) _
            AndAlso (users.Count > 0) Then
            With authorizedBy_DropDownList
                .DataSource = users
                .DataTextField = "Text"
                .DataValueField = "UserId"
                .DataBind()
            End With
        End If

    End Sub

    Private Sub Refresh_AccessRecords()

        Dim db As New DbHelper
        accessRecords_GridView.DataKeyNames = {"Id"}
        accessRecords_GridView.DataSource = db.GetAccessRecordList_Pending
        accessRecords_GridView.DataBind()

    End Sub

    Private Sub issuePass_Button_Click(sender As Object, e As System.EventArgs) Handles issuePass_Button.Click

        Dim db As New DbHelper
        Dim ar As New AccessRecordType
        With ar
            If (hdCustID.Value IsNot Nothing) _
                AndAlso (hdCustID.Value <> "") Then
                .CustomerId = New Guid(hdCustID.Value)
            End If
            .PassId = New Guid(passNo_DropDownList.SelectedValue)
            If (authorizedBy_DropDownList.SelectedValue IsNot Nothing) _
                AndAlso (authorizedBy_DropDownList.SelectedValue <> "") Then
                .AuthorizedByUserId = New Guid(authorizedBy_DropDownList.SelectedValue)
            End If
            .Purpose = purpose_TextBox.Text
            If (authorizedBy_DropDownList.SelectedValue IsNot Nothing) _
                AndAlso (authorizedBy_DropDownList.SelectedValue <> "") Then
                .AuthorizedByUserId = New Guid(authorizedBy_DropDownList.SelectedValue)
            End If
            Dim loggedUser As UserType = AuthenticationValidator.GetLoggedInUser(Me)
            .IssuedByUserId = loggedUser.UserId
            .IssuedDate = DateTime.Now
            .RetrievedByUserId = Guid.Empty
            .RetrievedDate = DateTime.MinValue
        End With

        Try
            db.IssuePass(ar)
            info_Label.Text = ""
            hdCustID.Value = Nothing
            customer_TextBox.Text = ""
            purpose_TextBox.Text = ""
            passNo_DropDownList.ClearSelection()
            passNo_DropDownList.Items.Clear()
            Refresh_Passes()
            Refresh_AccessRecords()
        Catch ex As Exception
            info_Label.Text = ex.Message
        End Try

    End Sub

    Private Sub accessRecords_GridView_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles accessRecords_GridView.RowCommand

        If e.CommandName = "Retrieve" Then
            Dim i As Integer = e.CommandArgument
            If (accessRecords_GridView.DataKeys(i) IsNot Nothing) _
                AndAlso (accessRecords_GridView.DataKeys(i).Value IsNot Nothing) Then
                RetrieveRecord(accessRecords_GridView.DataKeys(i).Value)
            End If
        ElseIf e.CommandName = "Lost" Then
            Dim i As Integer = e.CommandArgument
            If (accessRecords_GridView.DataKeys(i) IsNot Nothing) _
                AndAlso (accessRecords_GridView.DataKeys(i).Value IsNot Nothing) Then
                LostRecord(accessRecords_GridView.DataKeys(i).Value)
            End If
        End If

    End Sub

    Private Sub accessRecords_GridView_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles accessRecords_GridView.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then

            'Get information bound to the row
            Dim drv As DataRowView = e.Row.DataItem
            Dim IssuedPassNo As String = drv.Item("IssuedPassNo")
            Dim CustomerIdNumber As String = drv.Item("CustomerIdNumber")
            Dim CustomerName As String = drv.Item("CustomerName")
            Dim customer As String = CustomerName & " (" & CustomerIdNumber & ")"

            'reference the retreive LinkButton
            Dim rButton As LinkButton = CType(e.Row.Cells(e.Row.Cells.Count - 2).Controls(0), LinkButton)

            rButton.OnClientClick = String.Format( _
                "return confirm('Are you sure you want to mark pass no {0} issued to {1} as retrieved, note that this action cannot be undone?');", _
                IssuedPassNo.Replace("'", "\'"), _
                customer.Replace("'", "\'"))

            'reference the lost LinkButton
            Dim lButton As LinkButton = CType(e.Row.Cells(e.Row.Cells.Count - 1).Controls(0), LinkButton)

            lButton.OnClientClick = String.Format( _
                "return confirm('Are you sure you want to mark pass no {0} issued to {1} as lost, note that this action cannot be undone?');", _
                IssuedPassNo.Replace("'", "\'"), _
                customer.Replace("'", "\'"))

        End If

    End Sub

    Private Sub RetrieveRecord(arId As Guid)

        Dim db As New DbHelper
        Dim ar As AccessRecordType = db.GetAccessRecordById(arId)
        Dim user As UserType = AuthenticationValidator.GetLoggedInUser(Me)
        ar.RetrievedByUserId = user.UserId
        ar.RetrievedDate = DateTime.Now
        Try
            db.RetrievePass(ar)
            info_Label.Text = ""
            hdCustID.Value = Nothing
            customer_TextBox.Text = ""
            passNo_DropDownList.ClearSelection()
            passNo_DropDownList.Items.Clear()
            Refresh_Passes()
            Refresh_AccessRecords()
        Catch ex As Exception
            info_Label.Text = ex.Message
        End Try

    End Sub

    Private Sub LostRecord(arId As Guid)

        Dim db As New DbHelper
        Dim ar As AccessRecordType = db.GetAccessRecordById(arId)
        Dim user As UserType = AuthenticationValidator.GetLoggedInUser(Me)
        ar.RetrievedByUserId = user.UserId
        ar.RetrievedDate = DateTime.Now
        Try
            db.LostPass(ar)
            info_Label.Text = ""
            hdCustID.Value = Nothing
            customer_TextBox.Text = ""
            passNo_DropDownList.ClearSelection()
            passNo_DropDownList.Items.Clear()
            Refresh_Passes()
            Refresh_AccessRecords()
        Catch ex As Exception
            info_Label.Text = ex.Message
        End Try

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
        Refresh_AccessRecords()
        Refresh_Passes()
    End Sub



End Class